package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Account;
import com.example.entity.Admin;
import com.example.entity.User;
import com.example.exception.CustomException;
import com.example.mapper.AdminMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 管理员业务处理
 **/
@Service
public class AdminService {

    @Resource
    private AdminMapper adminMapper;

    /**
     * 登录
     */
    public Account login(Account account) {
        Account admin = adminMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(admin)) {
            throw new CustomException("该账号不存在，请先注册");
        }
        if (!account.getPassword().equals(admin.getPassword())) {
            throw new CustomException("账号或密码错误");
        }
        return admin;
    }

    /**
     * 添加管理员
     * @param admin
     */
    public void add(Admin admin){
        if(ObjectUtil.isEmpty(admin.getPassword())){
            admin.setPassword("1234");
        }
        admin.setRole("ADMIN");
        adminMapper.insert(admin);
    }

    /**
     * 删除管理员
     * @param id
     */
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            adminMapper.deleteById(id);
        }
    }

    /**
     * 修改昵称
     * @param admin
     */
    public void updateById(Admin admin){
        Admin selectAdmin = adminMapper.selectByUsername(admin.getUsername());
        if(admin.getNewPassword() != null){
            admin.setPassword(admin.getNewPassword());
        }
        if(selectAdmin.getName().equals(admin.getName()) && selectAdmin.getAvatar().equals(admin.getAvatar()) && admin.getNewPassword() == null){
            throw new CustomException("管理员资料未修改");
        }
        adminMapper.updateById(admin);
    }

    /**
     * 查询所有
     * @param admin
     * @return
     */
    public List<Admin> selectAll(Admin admin){
        return adminMapper.selectAll(admin);
    }

    /**
     * 分页查询
     * @param admin
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<Admin> selectPage(Admin admin, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }
}